#include "CocosPCH.h"
#include "ImageViewer.h"

bool ImageViewer::initUI()
{
    BaseViewer::initUI();

    m_strMaskTextureFormat = CCUserDefault::getInstance()->getStringForKey("MaskTextureFormat", "{1%s}_alpha{2%s}");

    return true;
}
ImageViewer::ImageViewer()
{
    m_bHasExportOne = true;
    m_bHasExportAll = true;
}

ui::Widget* ImageViewer::createItem(int nIndex, std::string strName)
{
    auto button = ui::Button::create("Button_Normal.png");
    button->setContentSize(Size(104, 40));
    button->setScale9Enabled(true);
    button->setTitleText(strName);
    button->setTitleFontSize(15);
    button->setTitleColor(Color3B(0, 0, 0));

    return button;
}

void ImageViewer::Export(std::string strPath)
{
    Data data = FileUtils::getInstance()->getDataFromFile(strPath);

    int nIndex = strPath.find_last_of("\\/");
    strPath = strPath.substr(0, nIndex + 1);
    strPath = strPath + "Image/";

    std::string strToDir = strPath;
    Utility_ConvertUtf8ToGBK(strToDir);
    Utility_ExportImageFromTexture(m_strFilePath.c_str(), strToDir.c_str());
}

bool ImageViewer::LoadFile(std::string strPath)
{
    BaseViewer::LoadFile(strPath);

    std::string strTextureName = strPath.c_str();

    Texture2D *pTexture = Director::getInstance()->getTextureCache()->addImage(strTextureName);
    std::string strName = Utility_GetFileName(strTextureName);
    std::string strExt = Utility_GetFileExt(strTextureName);

    if (strExt == ".pkm")
    {
        std::string strMaskTexture = Utility_StringFormat2(m_strMaskTextureFormat.c_str(), strName.c_str(), strExt.c_str());
        if (CCFileUtils::getInstance()->isFileExist(strMaskTexture.c_str()))
        {
            Texture2D *pMaskTexture = Director::getInstance()->getTextureCache()->addImage(strMaskTexture);
            if (pMaskTexture)
                pTexture->setMaskTexture(pMaskTexture);
        }
    }
    else if (strExt == ".ktx")
    {
        std::string strMaskTexture = Utility_StringFormat2("{1%s}.png", strName.c_str());
        if (CCFileUtils::getInstance()->isFileExist(strMaskTexture.c_str()))
        {
            Texture2D *pMaskTexture = Director::getInstance()->getTextureCache()->addImage(strMaskTexture);
            if (pMaskTexture)
                pTexture->setMaskTexture(pMaskTexture);
        }
    }

    CCSprite *pSpreite = CCSprite::createWithTexture(pTexture);

    Size size = pSpreite->getContentSize();
    Size viewSize = getContentSize();

    float fScaleX = viewSize.width / size.width;
    float fScaleY = viewSize.height / size.height;
    float fScale = std::min(fScaleX, fScaleY);
    fScale = std::min(1.0f, fScale);
    pSpreite->setScale(fScale);
    pSpreite->setPosition(viewSize*0.5);

    m_pViewNode->addChild(pSpreite);

    return true;
}

void ImageViewer::ClearCache()
{
    if (m_strFilePath.size() > 0)
        Director::getInstance()->getTextureCache()->removeTextureForKey(m_strFilePath.c_str());
}